<template>
  <div class="app-container">
    <div class="mainbox">
      <dt-table
        v-loading="loading"
        :table-opts="tableOpts"
        :pagination-data="{
          total:total,
          queryParams:queryParams
        }"
        @pagination="getList"
        @searchChange="handleQuery"
        @searchReset="handleReset"
      />
      <!-- 添加或修改单点认证对话框 -->
      <dt-dialog :title="title" :visible.sync="open" :is-loading="loading"
                 @comfirmBtn="submitForm" @closeDialog="cancel">
        <div slot="content">
          <el-form ref="form" :model="form" :rules="rules"
                   label-width="188px">
            <el-form-item label="应用名称" prop="appObj">
              <el-select v-model="appObj" value-key="appId" placeholder="请选择应用名称"
                         clearable size="small" style="width:100%;"
                         @change="selectAppName()">
                <el-option
                  v-for="item in ApplicationMagList"
                  :key="item.appId"
                  :label="item.appName"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="应用编码" prop="appCode">
              <el-input v-model.trim="form.appCode" disabled placeholder="请输入应用编码" />
            </el-form-item>
            <el-form-item label="应用密钥" prop="appSecret">
              <el-input v-model.trim="form.appSecret" disabled placeholder="请输入应用密钥" />
            </el-form-item>
            <el-form-item label="应用客户端ID" prop="appClientId">
              <el-input v-model.trim="form.appClientId" disabled placeholder="请输入应用客户端ID" />
            </el-form-item>
            <!-- <el-form-item label="登录回调地址" prop="loginCallbackAddress">
              <el-input v-model.trim="form.loginCallbackAddress" placeholder="请输入回调地址" maxlength="200" show-word-limit class="limit" />
            </el-form-item> -->
            <el-form-item label="应用域名(地址)" prop="appHost">
              <el-input v-model.trim="form.appHost" placeholder="请输入应用域名" disabled />
            </el-form-item>
            <el-form-item label="是否统一登出" prop="singleLogout">
              <el-radio-group v-model="form.singleLogout" @change="change('form')">
                <el-radio
                  v-for="dict in dict.type.UnifiedLogout"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="退出登录回调地址" prop="logoutCallbackAddress" :rules="form.singleLogout == '1' ? rules.logoutCallbackAddress : [{ required: false }]">
              <el-input v-model.trim="form.logoutCallbackAddress" placeholder="请输入退出登录回调地址" maxlength="200"
                        show-word-limit class="limit" />
            </el-form-item>
            <el-form-item label="认证方式" prop="authMode">
              <el-radio-group v-model="form.authMode" @change="change('form')">
                <el-radio
                  v-for="dict in dict.type.AuthWay"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- CAS认证 -->
            <!-- <div v-if="form.authMode=='1'">
              <el-form-item label="CAS服务器登录地址" prop="casLoginAddress">
                <el-input v-model.trim="form.casLoginAddress" :disabled="false" maxlength="100" show-word-limit placeholder="请输入CAS服务器登录地址" class="limit" />
              </el-form-item>
              <el-form-item label="CAS服务器验证票据地址" prop="casVerifyBillAddress">
                <el-input v-model.trim="form.casVerifyBillAddress" maxlength="100" show-word-limit placeholder="请输入CAS服务器验证票据地址" class="limit" />
              </el-form-item>
              <el-form-item label="CAS服务器登出地址" prop="casLogoutAddress">
                <el-input v-model.trim="form.casLogoutAddress" maxlength="100" show-word-limit placeholder="请输入CAS服务器登出地址" class="limit" />
              </el-form-item>
            </div> -->
            <!-- OAuth2认证 -->
            <!-- <div v-if="form.authMode=='2'">
              <el-form-item label="认证接口地址" prop="authInterfaceAddress">
                <el-input v-model.trim="form.authInterfaceAddress" maxlength="100" show-word-limit placeholder="请输入认证接口地址" class="limit" />
              </el-form-item>
              <el-form-item label="获取令牌接口地址" prop="getTokenAddress">
                <el-input v-model.trim="form.getTokenAddress" maxlength="100" show-word-limit placeholder="请输入获取令牌接口地址" class="limit" />
              </el-form-item>
              <el-form-item label="获取用户信息接口地址" prop="getUserInfoAddress">
                <el-input v-model.trim="form.getUserInfoAddress" maxlength="100" show-word-limit placeholder="请输入获取用户信息接口地址" class="limit" />
              </el-form-item>
              <el-form-item label="刷新授权令牌接口地址" prop="refreshTokenAddress">
                <el-input v-model.trim="form.refreshTokenAddress" maxlength="100" show-word-limit placeholder="请输入刷新授权令牌接口地址" class="limit" />
              </el-form-item>
              <el-form-item label="应用密钥" prop="clientSecret">
                <el-input v-model.trim="form.clientSecret" maxlength="100" show-word-limit placeholder="请输入应用密钥" class="limit" />
              </el-form-item>
            </div> -->
            <!-- Restful 认证-->
            <!-- <div v-if="form.authMode=='3'">
              <el-form-item label="登录地址" prop="restfulLoginAddress">
                <el-input v-model.trim="form.restfulLoginAddress" maxlength="100" show-word-limit placeholder="请输入登录地址" class="limit" />
              </el-form-item>
              <el-form-item label="应用密钥" prop="restfulClientSecret">
                <el-input v-model.trim="form.restfulClientSecret" maxlength="100" show-word-limit placeholder="请输入应用密钥" class="limit" />
              </el-form-item>
            </div> -->
          </el-form>
        </div>
      </dt-dialog>
    </div>
  </div>
</template>

<script>
import { listApp, getApp, delApp, addApp, updateApp, getThirdAppList } from '@/framework/api/authenticationCenter/singlePointAuth/singlePointAuth'
import { isExternal } from '@/framework/utils/validate'

export default {
  name: 'SinglePointAuth',
  dicts: ['AuthWay', 'UnifiedLogout'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显隐表格
      isShowTable: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应用管理列表
      ApplicationMagList: [],
      appObj: {},
      // 单点认证表格数据
      // SinglePointAuthList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        appName: null,
        authMode: null
      },
      tableOpts: {
        rowKey: 'id',
        toolbarBtn: [
          {
            label: '新增',
            permission: ['SINGLEPOINTAUTH_ADD_BUTTON'],
            icon: 'el-icon-plus',
            type: 'primary',
            click: () => {
              this.handleAdd()
            }
          }
        ],
        firstTableCol: {
          select: false,
          width: 70
        },
        indexTableCol: {
          label: '序号',
          width: 70
        },
        tableCol: [
          {
            prop: 'appName',
            label: '应用名称',
            show: true,
            search: true
          },
          {
            prop: 'appCode',
            label: '应用编码',
            show: true
          },
          {
            prop: 'appSecret',
            label: '应用密钥',
            show: true
          },
          {
            prop: 'appClientId',
            label: '应用客户端id',
            show: true
          },
          // {
          //   prop: 'loginCallbackAddress',
          //   label: '登录回调地址',
          //   show: true
          // },
          // {
          //   prop: 'logoutCallbackAddress',
          //   label: '退出登录回调地址',
          //   show: true
          // },
          {
            prop: 'appHost',
            label: '应用域名(地址)',
            show: true
          },
          {
            prop: 'authMode',
            label: '认证方式',
            show: true,
            search: true,
            type: 'dict',
            formatter: () => { return this.dict.type.AuthWay }
          }
        ],
        operator: {
          fixed: 'right',
          align: 'center',
          width: 204,
          operatorBtn: [
            {
              text: '修改',
              permission: ['SINGLEPOINTAUTH_UPDATE_BUTTON'],
              icon: 'el-icon-edit',
              click: (row, col, cellValue) => {
                return this.handleUpdate(row)
              }
            },
            {
              text: '删除',
              permission: ['SINGLEPOINTAUTH_DEL_BUTTON'],
              icon: 'el-icon-delete',
              type: 'danger',
              click: (row, col, cellValue) => {
                return this.handleDelete(row)
              }
            }
          ]
        },
        tableData: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        appObj: [
          { required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (Object.keys(this.appObj).length <= 0) {
                callback(new Error('应用名称不能为空'))
              } else callback()
            }
          }
        ],
        appCode: [
          { required: true, message: '应用编码不能为空', trigger: 'change' }
        ],
        appSecret: [
          { required: true, message: '应用密钥不能为空', trigger: 'change' }
        ],
        appClientId: [
          { required: true, message: '应用客户端Id不能为空', trigger: 'blur' }
        ],
        loginCallbackAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('登录回调地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('登录回调地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        singleLogout: [{ required: true, message: '是否统一登出不能为空', trigger: 'blur' }],
        logoutCallbackAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('退出登录回调地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('回调地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        appHost: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('应用域名不能为空'))
              } else {
                callback()
              }
            // else if (!isExternal(value)) {
            //   callback(new Error('应用域名必须以http://或https://开头'))
            // }
            }
          }
        ],
        authMode: [
          { required: true, message: '认证方式不能为空', trigger: 'blur' }
        ],
        casLoginAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('CAS服务器登录地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('CAS服务器登录地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        casVerifyBillAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('CAS服务器验证票据地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('CAS服务器验证票据地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        casLogoutAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('CAS服务器登出地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('CAS服务器登出地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        authInterfaceAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('认证接口地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('认证接口地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        getTokenAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('获取令牌接口地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('获取令牌接口地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        getUserInfoAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('获取用户信息接口地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('获取用户信息接口地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        refreshTokenAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('刷新授权令牌接口地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('刷新授权令牌接口地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        clientSecret: [
          { required: true, message: '应用密钥不能为空', trigger: 'blur' }
        ],
        loginAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('登录地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('登录地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        restfulLoginAddress: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('登录地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('登录地址必须以http://或https://开头'))
              } else {
                callback()
              }
            }
          }
        ],
        restfulClientSecret: [
          { required: true, message: '应用密钥不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.getList()
    },
    /** 查询单点认证列表 */
    getList() {
      this.loading = true
      listApp(this.queryParams).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      })
    },
    getApp() {
      getThirdAppList().then((res) => {
        this.ApplicationMagList = res.data
      })
    },
    selectAppName() {
      this.form.appId = this.appObj.appId
      this.form.appCode = this.appObj.appCode
      this.form.appSecret = this.appObj.appSecret
      this.form.appClientId = this.appObj.appClientId
      this.form.appHost = this.appObj.appHost
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        appName: null,
        appCode: null,
        appSecret: null,
        authMode: null,
        address: null,
        casLoginAddress: null,
        casVerifyBillAddress: null,
        singleLogout: null,
        casLogoutAddress: null,
        clientSecret: null,
        appClientId: null,
        appHost: null,
        authInterfaceAddress: null,
        getTokenAddress: null,
        getUserInfoAddress: null,
        refreshTokenAddress: null,
        loginAddress: null,
        restfulLoginAddress: null,
        restfulClientSecret: null
      }
      this.appObj = {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery(formModel) {
      this.queryParams = Object.assign(this.queryParams, formModel)
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryParams = {
        appName: '',
        authMode: '',
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加单点认证'
      this.form.authMode = 1
      this.form.singleLogout = '2'
      this.getApp()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getApp(row.id).then((response) => {
        this.form = response.data
        this.appObj = this.form.appName
        this.open = true
        this.title = '修改单点认证'
      })
    },
    /** 单选框切换 */
    change() {
      this.$refs.form.clearValidate()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateApp(this.form).then((response) => {
              this.$dtModal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addApp(this.form).then((response) => {
              this.$dtModal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$dtModal.confirm(`是否确认删除应用名称为"${row.appName}"的数据项？`).then(() => {
        return delApp(row.id)
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
      }).catch(() => {})
    }
  }
}
</script>

